package com.wannengbang.storemobile;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.multidex.MultiDex;

import com.alibaba.idst.token.AccessToken;
import com.alibaba.idst.util.NlsClient;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.MeizuRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.alibaba.sdk.android.push.register.VivoRegister;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.tencent.bugly.beta.ui.UILifecycleListener;
import com.tencent.bugly.crashreport.CrashReport;
import com.wannengbang.storemobile.base.DataCallBack;
import com.wannengbang.storemobile.bean.BaseResponseBean;
import com.wannengbang.storemobile.homepage.model.HomePageModelImpl;
import com.wannengbang.storemobile.utils.DisplayUtil;
import com.wannengbang.storemobile.utils.SPManager;
import com.wannengbang.storemobile.utils.VersionUtil;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class MyApplication extends Application {

    private static final String TAG = "AliPushInit";
    private static Context context;
    private static Application application;
    private static String client_type;
    private static String client_version;
    private static String is_weixin;
    private static String oem_no;
    private static String oem_app_id;
    private static NlsClient client;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // 将MultiDex注入到项目中
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 第一步，创建client实例，client只需要创建一次，可以用它多次创建synthesizer
        client = new NlsClient();

        application = this;
        context = getApplicationContext();
        DisplayUtil.init(this);
        initParameter();
        if (!TextUtils.isEmpty(SPManager.getInstance().getProtocol())) {
            initCloudChannel(this);
            initThridCloudChannel();
            initCrashReport();
            initSpeechToken();
        }
    }

    public void initParameter() {
        //1-android 2-ios
        client_type = "1";
        client_version = String.valueOf(VersionUtil.packageName(getApplicationContext()));
        is_weixin = "0";
        oem_no = "wannengbang";
        oem_app_id = "1";
    }

    public static Context getContext() {
        return context;
    }

    public static Application getApplication() {
        return application;
    }

    public static String getClient_type() {
        return client_type;
    }

    public static String getClient_version() {
        return client_version;
    }

    public static String getIs_weixin() {
        return is_weixin;
    }

    public static String getOem_no() {
        return oem_no;
    }

    public static NlsClient getClient() {
        return client;
    }

    public static String getOem_app_id() {
        return oem_app_id;
    }

    /**
     * 得到语音合成 的token
     */
    public void initSpeechToken() {
        String speechToken = SPManager.getInstance().getSpeechToken();
        if (TextUtils.isEmpty(speechToken)) {
            refreshSpeechToken();
        } else {
            long expireTime = Long.parseLong(speechToken.split("_")[1]);
            if (expireTime < System.currentTimeMillis()) {
                refreshSpeechToken();
            }
        }
    }

    /**
     * 刷新token
     */
    public void refreshSpeechToken() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    AccessToken token = new AccessToken("LTAIN2UMfywjKdR9", "qFEjfZkY3LjP87bJLhlG0zxdZOlOPj");
                    token.apply();
                    String accessToken = token.getToken();
                    long expireTime = token.getExpireTime() * 1000;
                    SPManager.getInstance().saveSpeechToken(accessToken, expireTime + "");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 初始化云推送通道
     *
     * @param applicationContext
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Log.d(TAG, "init cloudchannel success deviceId : " + pushService.getDeviceId());
                if (!TextUtils.isEmpty(SPManager.getInstance().getToken())) {
                    new HomePageModelImpl().requestbindDeviceId(pushService.getDeviceId(), new DataCallBack<BaseResponseBean>() {
                        @Override
                        public void onSuccessful(BaseResponseBean bean) {

                        }

                        @Override
                        public void onFailed(String msg, String code) {

                        }
                    });
                }
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.d(TAG, "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }

    public void initThridCloudChannel() {
        // 注册方法会自动判断是否支持小米系统推送，如不支持会跳过注册。
        MiPushRegister.register(application, "2882303761518288639", "5751828843639");
        // 注册方法会自动判断是否支持华为系统推送，如不支持会跳过注册。
        HuaWeiRegister.register(application);
        //GCM/FCM辅助通道注册
        //GcmRegister.register(this, "", ""); //sendId/applicationId为步骤获得的参数
        // OPPO通道注册
        OppoRegister.register(application, "a2be5714cf6c4578abf23b96217d942e", "6000354e06b3418dba2dbd3e801b67bd"); // appKey/appSecret在OPPO开发者平台获取
        // 魅族通道注册
        MeizuRegister.register(application, "130856", "2f1c3f6a8ec04b21821bf31af1f63ff5"); // appId/appkey在魅族开发者平台获取
        // VIVO通道注册
        VivoRegister.register(application);
    }

    /**
     * 腾讯bugly
     */
    public void initCrashReport() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));

        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;
        Beta.upgradeDialogLifecycleListener = new UILifecycleListener<UpgradeInfo>() {
            @Override
            public void onCreate(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onCreate");
            }

            @Override
            public void onStart(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onStart");
            }

            @Override
            public void onResume(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onResume" + upgradeInfo.upgradeType);
                View view_line = view.findViewById(R.id.view_line);
                if (upgradeInfo.upgradeType == 2) {
                    view_line.setVisibility(View.GONE);
                }
            }

            @Override
            public void onPause(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onPause");
            }

            @Override
            public void onStop(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onStop");
            }

            @Override
            public void onDestroy(Context context, View view, UpgradeInfo upgradeInfo) {
                Log.d(TAG, "onDestory");
            }
        };
        Bugly.init(getApplicationContext(), "60bdcbb141", true);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
